﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Management.Automation;
using PowerOBIProvider;
using PowerOBIProvider.OBI;
using PowerOBIPRovider.OBIWebReference;
using System.Collections.ObjectModel;

namespace PowerOBIProvider.Cmdlts
{
    [Cmdlet("Invoke","OBISQL")]
    public class InvokeOBISQLCmdlt: BaseOBICmdlt
    {
        private string drive = null;
        [Parameter(Mandatory = false, Position = 1)]
        [ValidateNotNullOrEmpty]
        public string Drive
        {
            get
            {
                return drive;
            }
            set
            {
                drive = value;
            }
        }

        private string obiSQL = null;
        [Parameter(Mandatory = true, Position = 2)]
        [ValidateNotNullOrEmpty]
        public string ObiSQL
        {
            get
            {
                return obiSQL;
            }
            set
            {
                obiSQL = value;
            }

        }
        private int maxRowsPerPage = 10;
        [Parameter(Mandatory = false, Position = 3)]
        [ValidateNotNullOrEmpty]
        public int MaxRowsPerPage
        {
            get
            {
                return maxRowsPerPage;
            }
            set
            {
                maxRowsPerPage = value;
            }
        }
        private bool direct = false;
        [Parameter(Mandatory = false, Position = 4)]
        [ValidateNotNullOrEmpty]
        public SwitchParameter Direct
        {
            get
            {
                return direct;
            }
            set
            {
                direct = value;
            }
        }
        protected override void ProcessRecord()
        {
            PSOBIDriveInfo obiDrive = null;
            if ( drive == null )
            {
                obiDrive = GetOBIDrive(SessionState.Path.CurrentLocation);
            }
            else
            {
                obiDrive = SessionState.Drive.Get(drive) as PSOBIDriveInfo;
            }
            QueryResults results = null;
            try
            {
                results = obiDrive.ObiWSClient.ExecuteSQLQuery(ObiSQL, MaxRowsPerPage, Direct);
                WriteObject(results);
            }
            catch ( Exception ex )
            {
                WriteError(new ErrorRecord(ex, "0", ErrorCategory.OperationStopped, null));
            }
        }
    }
}
